package com.zb.service;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayUtil;
import com.zb.util.HttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class PayService {

    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.partner}")
    private String partner;
    @Value("${weixin.partnerkey}")
    private String partnerkey;
    @Value("${weixin.notifyurl}")
    private String notifyurl;

    public Map<String, String> create(String orderId, Integer money,String flag,String username) {
       Map<String,String>param=new HashMap<>();
       param.put("appid", appid);
       param.put("mch_id", partner);
       param.put("nonce_str", WXPayUtil.generateNonceStr());
       param.put("body", "我的商城");
       param.put("out_trade_no", orderId);
       param.put("total_fee", money.toString());
       param.put("spbill_create_ip", "127.0.0.1");
       param.put("notify_url", notifyurl);
       param.put("trade_type", "NATIVE");
       Map<String,String>attach=new HashMap<>();
       attach.put("flag", flag);
        attach.put("username", username);
       param.put("attach", JSON.toJSONString(attach));
        try {
            String xml = WXPayUtil.generateSignedXml(param, partnerkey);
            String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            HttpClient httpClient = new HttpClient(url);
            httpClient.setHttps(true);
            httpClient.setXmlParam(xml);
            httpClient.post();
            Map<String, String> responseMap = WXPayUtil.xmlToMap(httpClient.getContent());
            return responseMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public Map<String, String> query(String orderId) {
        Map<String, String> param = new HashMap<>();
        param.put("appid", appid);
        param.put("mch_id", partner);
        param.put("nonce_str", WXPayUtil.generateNonceStr());
        param.put("out_trade_no", orderId);
        try {
            String xml = WXPayUtil.generateSignedXml(param, partnerkey);
            String url = "https://api.mch.weixin.qq.com/pay/orderquery";
            HttpClient httpClient = new HttpClient(url);
            httpClient.setHttps(true);
            httpClient.setXmlParam(xml);
            httpClient.post();
            Map<String, String> responseMap = WXPayUtil.xmlToMap(httpClient.getContent());
            return responseMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
